<template>
  <CommonPage :title="title">
    <template #mid>
      <SearchForm>
        <template #extraButtons>
          <a-button type="primary" @click="showCreateModal">
            {{ addBtnText }}
          </a-button>
        </template>
      </SearchForm>
    </template>
    <SlTable :columns="columns" row-key="id" :data-source="tableData" :pagination="pagination" :loading="tableLoading">
      <template #bodyCell="{ column, record }: BodyCellOptions<FinancialItem>">
        <div v-if="column.key === 'oper'">
          <!-- <a class="mr-2" @click="addSubMenu(record)"> 新增下级 </a> -->
          <div>
            <a v-if="record.status === ReceiptStatus.waiting" class="mr-2" @click="showUpdateModal(record)">编辑</a>
            <a class="text-red-400" @click="handleDelete(record)">删除</a>
          </div>
          <div v-if="record.status !== ReceiptStatus.disabled">
            <a v-if="record.status === ReceiptStatus.waiting" @click="handleReview(record)">审核</a>
            <span v-if="record.status === ReceiptStatus.waiting" class="inline-block w-2"></span>
            <a class="text-red-400" @click="handleNullify(record)">作废</a>
          </div>
        </div>
        <div v-else-if="column.key === 'extraOper' && pageType === 'CheckBill'">
          <a v-if="record.status === ReceiptStatus.passed" class="block" @click="handlePush(record)">推送</a>
          <a v-if="record.status === ReceiptStatus.confirmed" class="block" @click="handleReset(record)">
            重置对账单
          </a>
          <a v-if="record.status === ReceiptStatus.confirmed" class="block" @click="handleGenerate(record)">
            生成结算单
          </a>
        </div>
        <div v-else-if="column.key === 'createInfo'">
          <div>{{ handleValue(record.tabulator) }}</div>
          <div v-if="record.tabulationTime">{{ dayjs(record.tabulationTime).format("YYYY-MM-DD HH:mm") }}</div>
        </div>
        <div v-else-if="column.key === 'reviewInfo'">
          <div>{{ handleValue(record.reviewer) }}</div>
          <div v-if="record.reviewTime">{{ dayjs(record.reviewTime).format("YYYY-MM-DD HH:mm") }}</div>
        </div>
        <div v-else-if="column.key === 'pushInfo'">
          <div>{{ handleValue(record.pusher) }}</div>
          <div v-if="record.pushTime">{{ dayjs(record.pushTime).format("YYYY-MM-DD HH:mm") }}</div>
        </div>
        <StatusCell v-else-if="column.dataIndex === 'status'" :status="record.status" />
        <div v-else-if="column.dataIndex === 'invoiceUrl'">
          <a-image :fallback="DEFAULT_IMG_BASE64_STR" :src="record.invoiceUrl" :width="150" />
        </div>
        <div v-else-if="detailModalOptions && detailModalOptions.triggerKeys.includes(column.dataIndex)">
          <a @click="showDetail(record)">{{ record[column.dataIndex] }}</a>
        </div>
        <FitTitleCell v-else :record="record" :column="column" />
      </template>
    </SlTable>
    <slot />
    <CURDDialog
      ref="curdDialogIns"
      id-key="id"
      :columns="columns"
      :create-title="createTitle"
      :update-title="updateTitle"
      :delete-message="deleteMessage"
      :show-options="showOptions"
      :model="model"
      :model-form-setting="modelFormSetting"
      :table-data="tableData"
      :curd="curd"
      :reload-table="reloadTable"
      :get-detail="getDetail"
      forceModal
      @before-ok="$emit('beforeOk', $event)"
      @before-update-model="$emit('beforeUpdateModel', $event)"
    >
      <template #formSuffix>
        <slot name="formSuffix" />
      </template>
    </CURDDialog>
    <FullPageModal
      v-if="detailModalOptions"
      v-model:visible="detailVisible"
      :title="detailModalOptions.title"
      :get-container="getContainer"
      mask
      inset-cls="!inset-x-4 !inset-y-4"
      hide-footer
    >
      <a-skeleton v-if="detailModalOptions.loading" active loading :avatar="false" />
      <template v-else>
        <a-descriptions bordered :column="2">
          <a-descriptions-item v-for="(el, i) in desData" :key="i" :label="el.label">
            {{ el.value }}
          </a-descriptions-item>
        </a-descriptions>
        <slot name="detailCenter" />
        <div class="mt-4 text-lg font-semibold">
          <span>制单人:</span>
          <span class="ml-2">{{ detailModalOptions.data.tabulator }}</span>
          <span class="ml-7">制单时间:</span>
          <span class="ml-2">
            {{
              detailModalOptions.data.tabulationTime
                ? dayjs(detailModalOptions.data.tabulationTime).format("YYYY-MM-DD HH:mm:ss")
                : "--"
            }}
          </span>
        </div>
        <div v-if="detailModalOptions.data.reviewer" class="mt-4 text-lg font-semibold">
          <span>审核人:</span>
          <span class="ml-2">{{ detailModalOptions.data.reviewer }}</span>
          <span class="ml-7">审核时间:</span>
          <span class="ml-2">
            {{
              detailModalOptions.data.reviewTime
                ? dayjs(detailModalOptions.data.reviewTime).format("YYYY-MM-DD HH:mm:ss")
                : "--"
            }}
          </span>
        </div>
      </template>
      <slot name="detail" />
    </FullPageModal>
  </CommonPage>
</template>
<script setup lang="ts">
import { TableColumnProps, message } from "ant-design-vue";
import { BodyCellOptions, SelectOptionItem } from "/@/types/antd";
import { ReceiptStatus } from "/@/api/main/pis/models";
import { DetailModalOptions, FinancialItem } from "/@/api/main/financial/models";
import { Api, changeFinancialStatus } from "/@/api/main/financial";
import { useCURD } from "/@/hooks/useCURD";
import StatusCell from "/@/views/common/ReceiptManage/StatusCell.vue";
import FitTitleCell from "/@/components/FitTitleCell.vue";
import { CURDAction, CURDModalEvent, FormItemData, ShowCURDModalOptions } from "/@/components/CURDDialog/models";
import { computed, ref } from "vue";
import InfoModal from "/@/components/InfoModal";
import { DEFAULT_IMG_BASE64_STR } from "/@/utils/file";
import dayjs from "dayjs";
import { getLabelByValueFromEnum, handleDateRowRender, handleValue } from "/@/utils/common";

const props = defineProps<{
  title: string;
  addBtnText: string;
  columns: TableColumnProps<FinancialItem>[];
  getPageUrl: string;
  cudUrl: string;
  createTitle: string;
  updateTitle: string;
  deleteMessage: string;
  model: Partial<FinancialItem>;
  modelFormSetting: FormItemData<Partial<FinancialItem>>[];
  reviewApiKey?: keyof typeof Api;
  nullifyApiKey?: keyof typeof Api;
  getDetail?: (record: Partial<FinancialItem>) => Promise<Partial<FinancialItem>>;
  detailModalOptions?: DetailModalOptions;
  pageType?: "CheckBill";
}>();

const emits = defineEmits(["beforeOk", "beforeUpdateModel", "showDetail"]);

const { pagination, tableData, tableLoading, curd, reloadTable } = useCURD<FinancialItem>({
  getPageUrl: props.getPageUrl,
  cudUrl: props.cudUrl,
  deleteParamKey: "params",
});

const showOptions = ref<ShowCURDModalOptions>();
function showCreateModal() {
  showOptions.value = { action: CURDAction.CREATE };
}
function showUpdateModal(record: FinancialItem) {
  showOptions.value = { action: CURDAction.UPDATE, record };
}
function handleDelete(record: FinancialItem) {
  showOptions.value = { action: CURDAction.DELETE, record };
}
function handleReview(record: FinancialItem) {
  InfoModal.warningConfirm({
    title: "提示",
    content: "确认审核通过吗？",
    async onOk() {
      if (!props.reviewApiKey) return;
      const re = await changeFinancialStatus(props.reviewApiKey, record.id);
      if (re === undefined) {
        message.success("操作成功");
        reloadTable();
      }
    },
  });
}
function handleNullify(record: FinancialItem) {
  InfoModal.warningConfirm({
    title: "提示",
    content: "确认作废吗？",
    async onOk() {
      if (!props.nullifyApiKey) return;
      const re = await changeFinancialStatus(props.nullifyApiKey, record.id);
      if (re === undefined) {
        message.success("操作成功");
        reloadTable();
      }
    },
  });
}
/**
 * detail modal
 */
const detailVisible = ref(false);
const desData = computed<SelectOptionItem[]>(() => {
  if (props.detailModalOptions) {
    const desKeys = props.detailModalOptions.desKeys;
    const data = props.detailModalOptions.data;
    return desKeys.map((item) => {
      let key = "",
        isDate = false,
        customRender: any = null,
        enumInfo: any = null;
      if (typeof item === "object") {
        key = item.key;
        isDate = !!item.isDate;
        customRender = item.customRender;
        enumInfo = item.enumInfo;
      } else {
        key = item;
      }
      const target = props.columns.find((el) => el.dataIndex === key);
      let value = data[key];
      if (isDate) {
        value = handleDateRowRender({ text: value });
      } else if (customRender) {
        value = customRender(value);
      } else if (enumInfo) {
        value = getLabelByValueFromEnum(value, enumInfo.enumData, enumInfo.localKey);
      }
      return {
        key,
        label: target?.title as string,
        value,
      };
    });
  } else {
    return [];
  }
});
function getContainer() {
  return document.body;
}
function showDetail(record) {
  detailVisible.value = true;
  emits("showDetail", record);
}
/**
 * checkbill
 */
function handlePush(record: FinancialItem) {
  InfoModal.warningConfirm({
    content: "确认推送对账单吗?",
    async onOk() {
      const re = await changeFinancialStatus("checkBillPush", record.id);
      if (re) {
        message.success("推送成功");
        reloadTable();
      }
    },
  });
}
function handleReset(record: FinancialItem) {
  InfoModal.warningConfirm({
    content: "确认重置对账单吗?",
    async onOk() {
      const re = await changeFinancialStatus("checkBillReset", record.id);
      if (re) {
        message.success("推送成功");
        reloadTable();
      }
    },
  });
}
function handleGenerate(record: FinancialItem) {
  InfoModal.warningConfirm({
    content: "确认生成结算单吗?",
    async onOk() {
      const re = await changeFinancialStatus("checkBillGenerate", record.id);
      if (re) {
        message.success("推送成功");
        reloadTable();
      }
    },
  });
}
</script>
